package com.eight.paper.admin.service.impl;

import com.eight.common.constant.UserConstants;
import com.eight.common.core.domain.TreeSelect;
import com.eight.common.exception.ServiceException;
import com.eight.common.utils.DateUtils;
import com.eight.common.utils.StringUtils;
import com.eight.common.core.domain.entity.QuestionRepo;
import com.eight.paper.admin.mapper.QuestionRepoMapper;
import com.eight.paper.admin.service.IQuestionRepoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 试题题库章节Service业务层处理
 * 
 * @author eight
 * @date 2023-10-11
 */
@Service
public class QuestionRepoServiceImpl implements IQuestionRepoService 
{
    @Autowired
    private QuestionRepoMapper questionRepoMapper;

    /**
     * 查询试题题库章节
     * 
     * @param repoId 试题题库章节主键
     * @return 试题题库章节
     */
    @Override
    public QuestionRepo selectQuestionRepoByRepoId(Long repoId)
    {
        return questionRepoMapper.selectQuestionRepoByRepoId(repoId);
    }

    /**
     * 查询试题题库章节列表
     * 
     * @param questionRepo 试题题库章节
     * @return 试题题库章节
     */
    @Override
    public List<QuestionRepo> selectQuestionRepoList(QuestionRepo questionRepo)
    {
        return questionRepoMapper.selectQuestionRepoList(questionRepo);
    }

    /**
     * 新增试题题库章节
     * 
     * @param questionRepo 试题题库章节
     * @return 结果
     */
    @Override
    public int insertQuestionRepo(QuestionRepo questionRepo)
    {
        QuestionRepo info = questionRepoMapper.selectQuestionRepoByRepoId(questionRepo.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus()))
        {
            throw new ServiceException("试题题库章节停用，不允许新增");
        }
        if (!UserConstants.DEPT_NORMAL.equals(info.getDelFlag()))
        {
            throw new ServiceException("试题题库章节已删除，不允许新增");
        }
        questionRepo.setCreateTime(DateUtils.getNowDate());
        questionRepo.setAncestors(info.getAncestors() + "," + questionRepo.getParentId());
        return questionRepoMapper.insertQuestionRepo(questionRepo);
    }

    /**
     * 修改试题题库章节
     * 
     * @param questionRepo 试题题库章节
     * @return 结果
     */
    @Override
    public int updateQuestionRepo(QuestionRepo questionRepo)
    {
        questionRepo.setUpdateTime(DateUtils.getNowDate());
        return questionRepoMapper.updateQuestionRepo(questionRepo);
    }

    /**
     * 删除试题题库章节信息
     * 
     * @param repoId 试题题库章节主键
     * @return 结果
     */
    @Override
    public int deleteQuestionRepoByRepoId(Long repoId)
    {
        return questionRepoMapper.deleteQuestionRepoByRepoId(repoId);
    }

    /**
     * 检查题库章节名称是否唯一
     * @param questionRepo
     * @return
     */
    @Override
    public boolean checkRepoNameUnique(QuestionRepo questionRepo) {
        Long repoId = StringUtils.isNull(questionRepo.getRepoId()) ? -1L : questionRepo.getRepoId();
        QuestionRepo info = questionRepoMapper.checkRepoNameUnique(questionRepo.getRepoName(), questionRepo.getParentId());
        if (StringUtils.isNotNull(info) && info.getRepoId().longValue() != repoId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 根据ID查询所有子章节（正常状态）
     *
     * @param repoId 题库章节ID
     * @return 子章节数
     */
    @Override
    public int selectNormalChildrenRepoById(Long repoId) {
        return questionRepoMapper.selectNormalChildrenRepoById(repoId);
    }

    /**
     * 是否存在章节子节点
     *
     * @param repoId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildByRepoId(Long repoId) {
        return questionRepoMapper.hasChildByRepoId(repoId)>0;
    }

    /**
     * 是否存在试题
     * @param repoId
     * @return
     */
    @Override
    public boolean checkRepotExistQuestion(Long repoId) {
        return questionRepoMapper.checkRepoExistQuestion(repoId)>0;
    }

    /**
     * 查询试题题库章节列表
     *
     * @param repo 试题题库章节
     * @return 试题题库章节
     */
    @Override
    public List<TreeSelect> selectRepoTreeList(QuestionRepo repo) {
        List<QuestionRepo> repos = selectQuestionRepoList(repo);
        return buildRepoTreeSelect(repos);
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param repos 题库列表
     * @return 下拉树结构列表
     */
    public List<TreeSelect> buildRepoTreeSelect(List<QuestionRepo> repos)
    {
        List<QuestionRepo> repoTrees = buildRepoTree(repos);
        return repoTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }
    /**
     * 构建前端所需要树结构
     *
     * @param repos 题库列表
     * @return 树结构列表
     */
    public List<QuestionRepo> buildRepoTree(List<QuestionRepo> repos)
    {
        List<QuestionRepo> returnList = new ArrayList<QuestionRepo>();
        List<Long> tempList = repos.stream().map(QuestionRepo::getRepoId).collect(Collectors.toList());
        for (QuestionRepo repo : repos)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(repo.getParentId()))
            {
                recursionFn(repos, repo);
                returnList.add(repo);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = repos;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<QuestionRepo> list, QuestionRepo t)
    {
        // 得到子节点列表
        List<QuestionRepo> childList = getChildList(list, t);
        t.setChildren(childList);
        for (QuestionRepo tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<QuestionRepo> getChildList(List<QuestionRepo> list, QuestionRepo t)
    {
        List<QuestionRepo> tlist = new ArrayList<QuestionRepo>();
        Iterator<QuestionRepo> it = list.iterator();
        while (it.hasNext())
        {
            QuestionRepo n = (QuestionRepo) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getRepoId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<QuestionRepo> list, QuestionRepo t)
    {
        return getChildList(list, t).size() > 0;
    }

}
